<template>
  <div>
    <article class="main-breadcrumb">
      <el-breadcrumb separator="/" class="main-breadcrumb-wrap">
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">数据分析</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home" @click="crumbsClick">工艺数据分析</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item v-if="typeDialog">
          <span class="main-breadcrumb-sp">{{ crumbsStatus }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </article>
    <div class="nx-content" v-if="!typeDialog">
      <div class="flex-bet">
        <div class="left-title flex"></div>
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="">
            <el-cascader v-model="treeId" placeholder="请选择考场组织" :options="schoolArray" :props="{
                checkStrictly: false,
                value: 'id',
                label: 'name',
                children: 'nextDatas',
              }" @change="changeTreeItem" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="searchForm.technologyDeviceId" placeholder="请选择工艺设备" clearable>
              <el-option v-for="item in deviceArray" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker v-model="date" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" @change="handleDate" clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button v-allow="'140101'" type="primary" @click="onSubmit">查询</el-button>
            <el-button v-allow="'140101'" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="info" v-if="analysisData.length == 0"></div>
    <div v-for="(item, index) in analysisData" :key="index">
      <div class="info">
        <el-row class="content">
          <span class="title">{{ item.name }}</span>
        </el-row>
        <el-row class="content">
          <el-col :span="24">
            <div class="flexc">
              <div :id="'Line' + index" class="LineOne" ref="LineOne"></div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import { getDataAnalysisTechnologyChart } from '@/api/analysis'
import { getSchoolInfos } from '@/api/school'
import { getTechnologyDevices } from '@/api/technology'

export default {
  components: {},
  // 表格数据
  data() {
    return {
      // 查询字段
      searchForm: {
        examinationRoomId: '',
        technologyDeviceId: '',
        startDate: '',
        endDate: ''
      },
      analysisData: [],
      crumbsStatus: '', // 三级面包屑名称
      typeDialog: false,
      addEditIsDialog: false, // 添加编辑页面状态
      addEditStatus: 'add',
      addEditId: '', // 添加编辑rowid
      treeId: [], // 考场组织id集合
      schoolArray: [], // 考场组织集合
      deviceArray: [], // 设备集合
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      date: [], // 日期范围
      userType: '', // 用户类型（0超级管理员，1考场管理员）
      examinationRoomId: '' // 考场id
    }
  },
  // 初始化加载
  mounted() {
    this.userType = Number(window.localStorage.getItem('userType'))
    this.examinationRoomId = Number(window.localStorage.getItem('examinationRoomId'))
    if (this.userType == 1) {
      this.searchForm.examinationRoomId = this.examinationRoomId
    }

    // 获取考场组织
    this.getSchoolInfos()
  },
  // 自定义方法
  methods: {
    // 查询
    onSubmit() {
      if (!this.searchForm.technologyDeviceId || this.searchForm.technologyDeviceId == '') {
        this.$message({
          type: 'error',
          message: '请选择工艺设备'
        })
        return
      }

      if (!this.searchForm.startDate || this.searchForm.startDate == '') {
        this.$message({
          type: 'error',
          message: '请选择开始日期'
        })
        return
      }

      if (!this.searchForm.endDate || this.searchForm.endDate == '') {
        this.$message({
          type: 'error',
          message: '请选择结束日期'
        })
        return
      }

      getDataAnalysisTechnologyChart({
        id: this.searchForm.technologyDeviceId,
        startDate: this.searchForm.startDate,
        endDate: this.searchForm.endDate
      }).then((res) => {
        if (res.code == 200) {
          this.analysisData = res.data

          setTimeout(() => {
            if (this.analysisData) {
              for (let i = 0; i < this.analysisData.length; i++) {
                this.initLineData(this.analysisData[i], 'Line' + i)
              }
            }
          }, 500)
        }
      })
    },
    // 初始化折线数据
    initLineData(val, id) {
      let xDataList = val.xdata
      let yDataList = []
      let yTitleList = []

      // 遍历获取数据
      val.ydata.forEach((value) => {
        yDataList.push({
          name: value.name + '（' + value.unit + '）',
          type: 'line',
          smooth: true,
          data: value.data
        })
        yTitleList.push(value.name + '（' + value.unit + '）')
      })

      const chartDom = document.getElementById(id)
      const myChart = echarts.init(chartDom)
      let option
      option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: yTitleList
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xDataList
        },
        yAxis: {
          type: 'value'
        },
        series: yDataList
      }

      option && myChart.setOption(option)
    },
    // 重置
    resetForm() {
      this.searchForm = {
        examinationRoomId: '',
        technologyDeviceId: '',
        startDate: '',
        endDate: ''
      }

      if (this.userType == 1) {
        this.searchForm.examinationRoomId = this.examinationRoomId
      }

      // 清空
      this.treeId = []
      this.deviceArray = []
      this.date = []

      this.onSubmit()
    },
    // 编辑添加取消关闭
    closeAddEdit() {
      this.addEditIsDialog = false
      this.typeDialog = false
    },
    // 面包屑
    crumbsClick() {
      this.typeDialog = false
      this.addEditIsDialog = false
    },
    // 获取考场组织
    getSchoolInfos() {
      getSchoolInfos().then((res) => {
        if (res.code == 200) {
          this.schoolArray = res.data
        }
      })
    },
    // 考场组织下拉切换
    changeTreeItem(val) {
      let len = val.length
      if (val && len == 5) {
        this.searchForm.examinationRoomId = val[len - 1]

        // 获取设备列表
        this.getTechnologyDeviceList()
      } else {
        this.searchForm.examinationRoomId = ''
        this.treeId = []
      }
    },
    // 获取设备列表
    getTechnologyDeviceList() {
      if (!this.searchForm.examinationRoomId || this.searchForm.examinationRoomId == '') {
        return
      }

      getTechnologyDevices({ id: this.searchForm.examinationRoomId }).then((res) => {
        if (res.code == 200) {
          this.deviceArray = res.data
        }
      })
    },
    // 日期切换
    handleDate() {
      if (this.date && this.date.length == 2) {
        this.searchForm.startDate = this.date[0]
        this.searchForm.endDate = this.date[1]
      } else {
        this.searchForm.startDate = ''
        this.searchForm.endDate = ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
.main-breadcrumb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 76px;
  border-bottom: solid 20px #f2f2f2;
  padding-left: 20px;
  .main-breadcrumb-wrap {
    font-size: 16px;
    line-height: 68px;
    .main-breadcrumb-home {
      cursor: pointer;
      color: #666666;
      font-weight: bold;
    }
    .main-breadcrumb-sp {
      color: #666666;
      font-weight: bold;
    }
  }
}

.info {
  border-top: solid 20px #f2f2f2;
  padding: 20px;
}

.title {
  font-size: 22px;
  font-weight: bold;
}

.content {
  margin-bottom: 20px;
}

.chartClass {
  position: relative;
  top: 20px;
}

.flexc {
  display: flex;
  align-items: center;
  justify-content: center;
}

.LineOne {
  width: 95%;
  height: 400px;
}
</style>